//
//  MJListController.m
//  测试1.1
//
//  Created by 王志盼 on 15/2/4.
//  Copyright (c) 2015年 王志盼. All rights reserved.
//

#import "MJListController.h"
#import "MJShowTextController.h"
#import "MJListCell.h"
#import "MJDataGroup.h"
#import "MJTextData.h"
#import "MJWordData.h"


@interface MJListController ()
@property (nonatomic, strong) NSArray *datas;
/**
 *  不同文章使用的是同一个单词库，那么只需要在文章列表里面加载一次数据即可
 */
@property (nonatomic, strong) MJWordData *words;
@end

@implementation MJListController
- (MJWordData *)words
{
    if (_words == nil) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"words.plist" ofType:nil];
        NSArray *array = [NSArray arrayWithContentsOfFile:path];
        NSMutableDictionary *muDict = [[NSMutableDictionary alloc] init];
        for (NSDictionary *dict in array) {
            [muDict addEntriesFromDictionary:dict];
        }
        MJWordData *p = [MJWordData wordDataWithDict:muDict];
        _words = p;
    }
    return _words;
}

- (NSArray *)datas
{
    if (_datas == nil) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"text 2.plist" ofType:nil];
        NSArray *array = [NSArray arrayWithContentsOfFile:path];
        NSMutableArray *tmpArray = [[NSMutableArray alloc] init];
        
        for (NSDictionary *dict in array) {
            MJDataGroup *p = [MJDataGroup dataGroupWithDict:dict];
            [tmpArray addObject:p];
        }
        _datas = tmpArray;
    }
    return _datas;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    MJShowTextController *showText = segue.destinationViewController;
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    MJDataGroup *p = self.datas[indexPath.section];
    showText.article = [p.articles[indexPath.row] text];
    showText.words = self.words;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.datas.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.datas[section] articles].count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MJListCell *cell = [MJListCell listCellWithTableView:tableView];
    MJDataGroup *p = self.datas[indexPath.section];
    cell.data = p.articles[indexPath.row];
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [self.datas[section] groupName];
}
@end